//
//  KCStation.m
//  Jade
//
//  Created by king on 16/6/24.
//  Copyright © 2016年 KC. All rights reserved.
//

#import "KCStation.h"

const int KStationIdentifier = 0xFF00;

static NSMutableDictionary *StationRegistry = nil;

@interface KCStation()

@property(nonatomic,assign)int stationID;
@property(nonatomic,weak)id <KCStationDelegate> delegate;

@end

@implementation KCStation

+ (NSMutableDictionary *)sharedStationRegistry
{
    @synchronized(self) {
        if(StationRegistry == nil) {
            StationRegistry = [[NSMutableDictionary alloc] init];
        }
    }
    return StationRegistry;
}

+ (KCStation *)RegisterStation:(int)stationID delegate:(id<KCStationDelegate>)delegate{
    
    KCStation *station = [[KCStation alloc] initWithStationID:stationID delegate:delegate];
    [[KCStation sharedStationRegistry] setObject:station forKey:@(stationID)];
    return station;
    
}
+ (void)RevokeStation:(KCStation *)station
{
    if (station) {
        [[KCStation sharedStationRegistry] removeObjectForKey:@(station.stationID)];
    }
}

- (id)initWithStationID:(int)stationID delegate:(id<KCStationDelegate>)delegate
{
    if (self = [super init]) {
        _stationID = stationID;
        _delegate = delegate;
    }
    return self;
}

- (void)sendCargo:(int)destinationID
{
    KCCargo *cargo = [KCCargo Share:_stationID destinationID:destinationID cargoID:KUnknowDestination cargoObj:nil];
    [self transport:cargo];

}

- (void)sendCargo:(int)destinationID cargoObj:(id)cargoObj
{
    KCCargo *cargo = [KCCargo Share:_stationID destinationID:destinationID cargoID:KUnknowDestination cargoObj:cargoObj];
    [self transport:cargo];

}

- (void)sendCargo:(int)destinationID cargoID:(int)cargoID cargoObj:(id)cargoObj{

    KCCargo *cargo = [KCCargo Share:_stationID destinationID:destinationID cargoID:cargoID cargoObj:cargoObj];
    [self transport:cargo];

}

- (void)transport:(KCCargo *)cargo {
    
    int stationID = cargo.destinationID & KStationIdentifier;
    KCStation *station = [[KCStation sharedStationRegistry] objectForKey:@(stationID)];
    [station dispatch:cargo];
    
}

- (void)dispatch:(KCCargo *)cargo {
    
    [_delegate dispatch:cargo];
    
}

@end
